<template>
  <!--  分布分析-->
  <div id="index">
    <div class="crumbs">
      <header class="crumbs_arr_box">
        <span>分布分析</span>
        <span class="tool_main">
          <!-- 保存弹框页面-->
          <!--          <preser-vation></preser-vation>-->
          <!--          <i class="fgf"></i>-->
          <div class="rec-wrap">
            <i class="el-icon-refresh" style="font-size: 16px"></i>
            <div class="record" style="border: 1px solid #cccccc">
              <p style="background-color: #dcdfe6">更新时间: 6-30 22:50:37</p>
              <p>仅刷失效数据</p>
              <p>刷新全部数据</p>
            </div>
          </div>

          <el-tooltip
            class="tool_son"
            effect="light"
            content="下载数据"
            placement="bottom"
          >
            <i class="el-icon-download" @click="exportExcel"></i>
          </el-tooltip>
          <el-popover placement="bottom" width="300" v-model="visible">
            <div class="block_tool">
              <span class="left">抽样设置：</span>
              <el-slider
                :min="1"
                :step="1"
                :max="7"
                class="right"
                :show-tooltip="false"
              ></el-slider>
              <span style="display: flex; justify-content: flex-end">全量</span>
              <div
                class="button"
                style="
                  display: flex;
                  justify-content: flex-end;
                  margin-top: 10px;
                "
              >
                <el-button
                  style="
                    height: 30px;
                    line-height: 5px;
                    font-size: 12px;
                    border: none;
                  "
                  @click="visible = false"
                  >取消</el-button
                >
                <el-button
                  style="height: 30px; line-height: 5px; font-size: 12px"
                  type="success"
                  >确认</el-button
                >
              </div>
            </div>
            <i class="el-icon-more tool_son" slot="reference"></i>
          </el-popover>
        </span>
      </header>

      <div class="content-main">
        <div class="conduct">
          <p style="margin-left: 15px">用户进行</p>
          <div class="any events">
            <el-button class="thing" @click="eventTool" style="padding: 0 30px"
              >{{ currentInitEventGroup.cname || "任意事件" }}
              <i class="el-icon-arrow-down"></i>
            </el-button>

            <!--          内置选择框-->
            <Options
              v-if="eventshow"
              :initEventGroupDetail="initEventGroupDetail"
              :initEventGroup="initEventGroup"
              :currentEvent="currentInitEventGroup"
              @choInitEventEnd="choInitEventEnd"
              v-clickoutside="handleClickOutSide"
            ></Options>
          </div>
          <p style="margin-left: 8px">的</p>
          <div class="any">
            <times-box
              @event="choEvent2"
              @timeNumber="timeNumber"
              @click="frequency"
              :eventsName="currentInitEventGroup.eventId"
            >
            </times-box>
          </div>

          <!--          设置符号弹框-->
          <set-bubble></set-bubble>

          <el-tooltip
            class="item"
            effect="dark"
            content="若用户在一天内进行任意事件1 次，就记 1 次。"
            placement="top"
            style="margin-left: 15px"
          >
            <i class="el-icon-question"></i>
          </el-tooltip>
        </div>

        <div class="eventsatisfy">
          <div class="statis">
            <span>事件满足</span>
            <div class="screen" @click="editCond()">
              <i class="el-icon-plus"></i>
              筛选条件
            </div>
            <br />
            <CustomScreen
              ref="customScreenRef"
              :isSupName="true"
              :supName="currentInitEventGroup.eventId"
              :currentInitEventGroup="currentInitEventGroup.eventId"
            ></CustomScreen>
          </div>
        </div>

        <div class="userget">
          <div class="statis">
            <span>用户符合</span>
            <div class="screen" @click="editCond2()">
              <i class="el-icon-plus"></i>
              筛选条件
            </div>
            <CustomScreen
              ref="customScreenRef2"
              :isEvent="'false'"
            ></CustomScreen>
          </div>
        </div>

        <div class="check">
          <div class="see">
            <div class="see-left">
              <span>按</span>
              <div class="useract" @click="useactive">
                <el-button class="thing" style="width: auto; padding: 0 15px">
                  <i class="el-icon-s-unfold"></i>
                  {{
                    byXXXReadValues.cname
                      ? byXXXReadValues.cname
                      : "用户行为日期"
                  }}
                </el-button>
              </div>
              <span>查看</span>
            </div>

            <div class="see-right">
              <el-button
                class="analy"
                type="primary"
                :icon="icon"
                :disabled="isDoCompute !== 0"
                size="small"
                @click="searchFunnel()"
                >分析计算
                <template v-if="icon === 'el-icon-loading'"
                  >({{ backTime }}s)</template
                >
              </el-button>
            </div>
          </div>
        </div>
        <CategoryFiltering
          v-if="usershow"
          @choAttributeEnd="choAttributeEnd"
          :tabsHeadParams="byXXXReadtabsHeadParams"
          :tabsBodyParams="byXXXReadtabsBodyParams"
          v-clickoutside="handleClickOutSide"
        ></CategoryFiltering>
      </div>

      <div class="Chart">
        <!--        时间选择-->
        <div class="timeSelect">
          <div class="timeLeft">
            <timeRestrict
                    :oldTime="dateS"
                    :timeRestrict="timeRestrict"
                    @change="dateSChange"
            ></timeRestrict>
          </div>

          <div class="timeRight">
            <el-select
              v-model="select"
              placeholder="全部"
              style="width: 110px"
              @change="itemunit"
            >
              <el-option
                v-for="item in timeunit"
                :key="item.unit"
                :label="item.unit"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>

        <!--        内容展示-->
        <TableFunnel
          @getFilter="getFilter"
          :filter="filter"
          :userFilter="userFilter"
          :chodate="chodate"
          :currentEvent="currentInitEventGroup"
          :measureTypeText="measureTypeText"
          :measureType="measureType"
          :select="select"
          :byXXXReadValues="byXXXReadValues"
          :ltvReportResData="initChartViewData"
          ref="exportExcel"
        ></TableFunnel>
      </div>
    </div>
  </div>
</template>

<script>
//组件
import CustomScreen from "./customScreen";
import timeSelect from "./timeSelect";
import TimesBox from "./timesBox";
import SetBubble from "./setBubble";
import CategoryFiltering from "./categoryFiltering";
import Options from "./options";
import TableFunnel from "./tableFunnel";
import PreserVation from "../funnelAnalysis/preserVation";

//接口
import {
  propertyList,
  thinglGroup,
  thinglList,
  spreadCount,
} from "./spread.config";

import clickoutside from "element-ui/src/utils/clickoutside";

export default {
  name: "index",
  components: {
    PreserVation,
    SetBubble,
    TimesBox,
    CustomScreen,
    timeSelect,
    CategoryFiltering,
    Options,
    TableFunnel,
  },
  directives: { clickoutside },
  data() {
    return {
      /* 点击分析计算切换图表 */
      icon: "el-icon-search",
      /* 分析计算倒计时*/
      backTime: 60,
      /* 是否正在计算中*/
      isDoCompute: 0,
      /* 初始事件详情数组 */
      initEventGroupDetail: [],
      /* 当前初始事件选择事件 */
      currentInitEventGroup: {
        eventId: "_Anything",
        cname: "任意事件",
        id: -1,
      },
      /* 初始事件数组 */
      initEventGroup: [],
      //按XXX查看选择器的属性组
      byXXXReadtabsHeadParams: ["事件属性", "用户属性", "用户分群", "用户标签"],
      //按XXX查看选择器的属性值
      byXXXReadtabsBodyParams: [],
      //当前按XXX查看的数值
      byXXXReadValues: {},
      /* 用来渲染图表和列表的数据 */
      initChartViewData: {},
      /* 选择事件的类型 只在选择 次数 小时数 天数时生效*/
      measureType: "times",
      /* 表格显示字段参数 */
      measureTypeText: "次",
      eventshow: false,
      usershow: true,
      quency: false,
      show: false,
      visible: false,
      timeunit: [],
      select: "",
      choE: "任意事件",
      time: "次数",
      userday: "用户行为日期",
      res: {}, //任意事件
      num: {}, //用户行为进行
      measure: {},
      filterEvent: {
        //筛选
        conditions: [
          {
            field: "",
            function: "",
            params: "",
          },
        ],
      },
      chodate: [], //时间
      tabledata: [],
      inputName: "",
      filter: {},
      userFilter: {},
      type: "", //类型
      timeRestrict: {
        function: "absolute_time",
        params:[this.getBeforeDate(2), this.getBeforeDate()]
      }, // 动态时间参数

      startDate: this.getBeforeDate(2),
      endDate: this.getBeforeDate(),
      dateS: [], // 开始时间段
    };
  },
  watch: {
    currentContrastStep: function (val, oldval) {
      this.searchLtv();
    },
    currentInitEventGroup: function (val, oldval) {
      this.measure.eventId = val.eventId;
      let t = this;
      let param = {
        req: {
          events: [val.eventId],
          type: "event",
          needEventTime: true,
        },
        operationCtx: {},
      };
      propertyList(param)
        .then((res) => {
          if (res.data.success !== true) {
            t.$message.error(res.data.errorMessage);
            return;
          }
          t.byXXXReadtabsBodyParams[0] = res.data.value;
        })
        .catch((error) => {
          console.log("error = ", error);
        });
    },
    revenueEventItems: {
      handler: function (val, oldVal) {
        this.isChangeRows = !this.isChangeRows;
        if (this.isChangeRows === false) {
          this.doListenerRevenueEventItems();
        }
      },
      deep: true,
    },
  },
  mounted() {
    this.useactive();
    this.doByXXXReadtabsBodyParams();
    this.getThinglData();
    this.init();
    this.choEvent2(["times"]);
  },
  methods: {
    getBeforeDate(number) {
      let num = number;
      let date = new Date();

      let year = date.getFullYear();
      let mon = date.getMonth() + 1;
      let day = date.getDate();

      if (typeof num === "number") {
        if (day <= num) {
          if (mon > 1) {
            mon = mon - 1;
          } else {
            year = year - 1;
            mon = 12;
          }
        }

        date.setDate(date.getDate() - num);

        year = date.getFullYear();
        mon = date.getMonth() + 1;
        day = date.getDate();
      }

      return (
              year +
              "-" +
              (mon < 10 ? "0" + mon : mon) +
              "-" +
              (day < 10 ? "0" + day : day)
      );
    },
    dateSChange(newValue) {
      let { sendTimeArr, timeRestrict } = newValue;
      this.timeRestrict = timeRestrict
      this.dateS = [sendTimeArr[0], sendTimeArr[1]];
      this.startDate = sendTimeArr[0];
      this.endDate = sendTimeArr[1];
      let contrastStartDate = null;
      let contrastEndDate = null;
      if (this.dateD && this.dateD[0]) {
        let date = new Date(this.dateD[0]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastStartDate = year + "-" + mon + "-" + day;
      }
      if (this.dateD && this.dateD[1]) {
        let date = new Date(this.dateD[1]);
        let year = date.getFullYear();
        let mon = date.getMonth() + 1;
        let day = date.getDate();
        contrastEndDate = year + "-" + mon + "-" + day;
      }

      // this.$emit("conversion", {
      //   unit: this.unit,
      //   startDate,
      //   endDate,
      //   contrastStartDate,
      //   contrastEndDate,
      //   timeRestrict    // 动态时间配置集合
      // });
    },
    exportExcel() {
      this.$refs.exportExcel.exportExcel();
    },
    //点击外部时 关闭所有选择框
    init() {
      this.timeunit = [
        {
          unit: "全部",
          value: "all",
        },
        {
          unit: "一天内",
          value: "day",
        },
        {
          unit: "一周内",
          value: "week",
        },
        {
          unit: "一个月内",
          value: "month",
        },
      ];
      this.select = this.timeunit[1].value;
    },
    handleClickOutSide() {
      this.eventshow = false;
      this.usershow = false;
      this.$forceUpdate();
    },
    //获取事件分组和所有事件类型
    getThinglData() {
      let t = this;
      thinglGroup({
        req: {
          appId: JSON.parse(window.sessionStorage.getItem("appItem")).appId,
        },
        operationCtx: {},
      }).then((res) => {
        if (res.data.success !== true) {
          t.$message.error(res.data.errorMessage);
          return;
        }
        res.data.value[0].mateEventList.unshift({
          eventId: "_Anything",
          eventName: "任意事件",
          productCode: "dx",
        });
        t.initEventGroup = res.data.value;
      });
      thinglList({
        req: {
          appId: JSON.parse(window.sessionStorage.getItem("appItem")).appId,
        },
        operationCtx: {},
      }).then((res) => {
        if (res.data.success !== true) {
          t.$message.error(res.data.errorMessage);
          return;
        }
        res.data.value.list.unshift({
          appId: 1,
          cname: "任意事件",
          id: -1,
          eventId: "_Anything",
        });
        t.initEventGroupDetail = res.data.value.list;
      });
    },
    //选择初始事件结束
    choInitEventEnd(res) {
      this.currentInitEventGroup = res.mes;
      this.eventshow = !this.eventshow;
    },
    //获取按XXX查看选择器的属性值 事件属性以及用户属性 以下三个方法
    doByXXXReadtabsBodyParams() {
      let events = ["_Anything"];
      let type = "event";
      let t = this;

      t.byXXXReadtabsBodyParams = [];
      this.doByXXXReadtabsBodyParamsEvent(events, type, t);
    },
    doByXXXReadtabsBodyParamsEvent(events, type, t) {
      let param = {
        req: {
          events: events,
          type: "event",
          needEventTime: true,
        },
        operationCtx: {},
      };
      propertyList(param)
        .then((res) => {
          if (res.data.success !== true) {
            t.$message.error(res.data.errorMessage);
            return;
          }
          t.byXXXReadtabsBodyParams.push(res.data.value);
          type = "user";
          t.doByXXXReadtabsBodyParamsUser(events, type, t);
        })
        .catch((error) => {
          console.log("error = ", error);
        });
    },
    doByXXXReadtabsBodyParamsUser(events, type, t) {
      let param = {
        req: {
          events: events,
          type: type,
          needEventTime: true,
        },
        operationCtx: {},
      };
      propertyList(param)
        .then((res) => {
          if (res.data.success !== true) {
            t.$message.error(res.data.errorMessage);
            return;
          }
          t.byXXXReadtabsBodyParams.push(res.data.value);
          t.byXXXReadValuesUserProperties = res.data.value.list;
          t.byXXXReadtabsBodyParams.push({
            total: 1,
            list: [],
          });
          t.byXXXReadtabsBodyParams.push({
            total: 1,
            list: [],
          });
        })
        .catch((error) => {
          console.log("error = ", error);
        });
    },

    choAttributeEnd(type, attribute) {
      this.byXXXReadValues = attribute;
      if (type === 0) {
        this.type = "event";
      } else if (type === 1) {
        this.type = "user";
      }
      this.useactive();
    },
    eventTool() {
      this.eventshow = !this.eventshow;
      if (this.usershow) {
        this.usershow = true;
      }
    },
    frequency() {
      this.quency = !this.quency;
    },
    choEvent2(value) {
      switch (value[0]) {
        case "times": //次数
          this.timeunit = [
            {
              unit: "全部",
              value: "all",
            },
            {
              unit: "一天内",
              value: "day",
            },
            {
              unit: "一周内",
              value: "week",
            },
            {
              unit: "一个月内",
              value: "month",
            },
          ];
          break;
        case "period": //天数
          this.timeunit = [
            {
              unit: "全部",
              value: "all",
            },
            {
              unit: "一周内",
              value: "week",
            },
            {
              unit: "一个月内",
              value: "month",
            },
          ];
          break;
        case "hourperiod": //小时数
          this.timeunit = [
            {
              unit: "全部",
              value: "all",
            },
            {
              unit: "一天内",
              value: "day",
            },
          ];
          break;
        default:
          this.timeunit = [
            {
              unit: "全部",
              value: "all",
            },
            {
              unit: "一天内",
              value: "day",
            },
            {
              unit: "一周内",
              value: "week",
            },
            {
              unit: "一个月内",
              value: "month",
            },
          ];
          break;
      }

      this.select = this.timeunit[1].value;

      this.measure = {};

      if (value.length > 1) {
        //如果选择次数 时间 天数以外
        this.measure.eventId = this.currentInitEventGroup.eventId;
        this.measure.aggregator = value[1];
        this.measure.field =
          "event" + "." + this.currentInitEventGroup.eventId + "." + value[0];

        //当前选择类型  次数小时数框 默认是times
        this.measureType = "times";

        if (this.measure.aggregator === "uniqCount") {
          this.measureTypeText = "个";
        } else {
          this.measureTypeText = "";
        }
      } else {
        this.measureType = value[0];
        switch (this.measureType) {
          case "hourperiod":
            this.measureType = "period";
            this.measureTypeText = "小时";
            break;
          case "period":
            this.measureTypeText = "天";
            break;
          case "times":
            this.measureTypeText = "次";
        }
      }
    },
    itemunit(select) {
      console.log(select);
      this.select = select;
    },
    getFilter() {
      this.filter = this.$refs.customScreenRef.getFilterConditions();
      this.userFilter = this.$refs.customScreenRef2.getFilterConditions();
    },
    //次数
    timeNumber(item) {
      this.time = item;
    },
    //时间选择
    timeUnity(time) {
      this.chodate = time;
      console.log(this.chodate, 99);
    },
    //筛选条件
    editCond() {
      this.$refs.customScreenRef.editCond();
    },
    editCond2() {
      this.$refs.customScreenRef2.editCond();
    },
    useactive() {
      this.usershow = !this.usershow;
      if (this.eventshow) {
        this.eventshow = true;
      }
    },
    searchFunnel() {
      // if (this.$refs.customScreenRef.getFilterConditions() === false) return;
      // if (this.$refs.customScreenRef2.getFilterConditions() === false) return;
      let t = this;
      let byField = "";
      if (this.type === "event" && this.byXXXReadValues.name) {
        byField =
          "event." +
          this.currentInitEventGroup.eventId +
          "." +
          this.byXXXReadValues.name;
      } else if (this.type === "user" && this.byXXXReadValues.name) {
        byField = "user." + this.byXXXReadValues.name;
      }

      let params = {
        req: {
          eventId: this.currentInitEventGroup.eventId,
          filter: this.$refs.customScreenRef.getFilterConditions(),
          fromDate: this.startDate,
          toDate: this.endDate,
          measureType: this.measureType,
          samplingFactor: 64,
          unit: this.select,
          subjectId: "userId",
          userFilter: this.$refs.customScreenRef2.getFilterConditions(),
          rollupDate: false,
          byField: byField,
          subTaskType: "ADDICTIONS",
          requestId: "1625736618635:149634",
          measure: this.measure,
          timeRestrict:this.timeRestrict
        },
        operationCtx: {},
      };

      t.isDoCompute = 1;
      /* 替换按钮图标 表示加载中 */
      t.icon = "el-icon-loading";
      t.backTimeNumber();

      spreadCount(params)
        .then((res) => {
          t.icon = "el-icon-search";
          // 返回状态码返回状态如果不是 true，说明数据异常，需弹窗提示
          if (res.data.success !== true) {
            t.$message.error(res.data.errorMessage);
            return;
          }
          console.log(res);
          this.initChartViewData = res.data.value;
        })
        .catch((error) => {
          t.icon = "el-icon-search";
          console.log("error=", error);
        });
    },
    /* 分析计算到倒计时*/
    backTimeNumber() {
      if (this.icon !== "el-icon-search") {
        if (this.backTime >= 0) {
          this.backTime--;
          setTimeout(this.backTimeNumber, 1000);
        } else {
          t.$message.error("计算超时");
        }
      } else {
        this.isDoCompute = 0;
        this.backTime = 60;
        return;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
#index {
  width: 97%;
  margin: 0 auto;
  box-sizing: border-box;
  height: auto;
  font-size: 14px;

  .crumbs {
    .crumbs_arr_box {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .tool_main {
        font-size: 12px;
        font-weight: 500;
        color: #606266;
        letter-spacing: 2px !important;

        .select {
          margin: 0 6px;
        }

        .fgf {
          display: inline-block;
          width: 1px;
          height: 16px;
          background: #c0c4cc;
          margin: 0 8px;
        }

        .rec-wrap {
          position: relative;

          .record {
            width: 200px;
            height: auto;
            position: absolute;
            left: -100px;
            top: 100%;
            background-color: #fff;
            display: none;

            p {
              margin: 0;
              height: 28px;
              line-height: 28px;
            }
          }
        }

        .rec-wrap:hover {
          .record {
            display: block;
          }
        }

        .tool_son {
          font-size: 16px;
          margin: 0 8px;
          font-size: 0.26rem;
        }

        .tool_son:hover {
          color: #01b27a;
          font-weight: 600;
        }
      }
    }
  }

  .content-main {
    height: auto;
    background-color: white;
    border-radius: 8px;
    margin: auto;
    box-shadow: 0 2px 11px rgba(190, 202, 218, 0.17);
    .conduct {
      width: 98%;
      margin: auto;
      display: flex;
      border-bottom: 1px solid #e9f0f7;
      padding-top: 8px;
      align-items: center;

      .any {
        height: 32px;
        margin-right: 15px;
        margin-left: 15px;
        z-index: 100;
      }
    }

    .events {
      position: relative;

      .thing-main {
        position: absolute;
        top: 110%;
        background-color: #fff;
      }
    }

    .eventsatisfy,
    .userget,
    .check {
      width: 98%;
      height: auto;
      background-color: white;
      border-radius: 8px;
      margin: auto;

      .statis,
      .accord,
      .see {
        display: flex;
        justify-content: space-between;
        border-bottom: 1px solid #e9f0f7;
        padding: 15px;
        align-items: center;

        .screen,
        .useract {
          margin: 0 20px;
          color: #01b27a;
          cursor: pointer;
        }

        .analy {
          width: 192px;
          padding-left: 60px;
          position: relative;
          margin-right: -15px;
        }

        .see-left {
          display: flex;
          align-items: center;
        }
      }

      .statis {
        display: block;

        .screen {
          display: inline-block;
        }
      }

      .thing {
        &:hover {
          width: 200px;
          color: #307ef2;
        }
      }
    }
  }

  .Chart {
    height: auto;
    background-color: white;
    border-radius: 8px;
    margin: auto;
    margin: 30px 0;
    padding: 20px;

    .timeSelect {
      display: flex;
      justify-content: space-between;
    }
  }

  ::v-deep .el-button {
    height: 32px;
    line-height: 32px;
    padding: 4px;
    display: flex;
    align-items: center;
  }
}
</style>

<style scoped>
::v-deep .el-input--suffix .el-input__inner {
  height: 32px;
}

::v-deep.el-date-editor .el-range__icon {
  line-height: 29px;
}

::v-deep.el-date-editor .el-range-separator {
  line-height: 28px;
}

::v-deep.el-date-editor--datetimerange.el-input,
.el-date-editor--datetimerange.el-input__inner {
  height: 32px;
}

::v-deep.el-select .el-input .el-select__caret {
  line-height: 30px;
}
</style>
